#ifndef __HTTP_UTILS_HPP__
#define __HTTP_UTILS_HPP__

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <unordered_map>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "../src/Log.hpp"


/**
 * @brief 状态码及其描述的对应表
 * 设置为全局变量，只构造一次。
 * 如果放在函数StatusCodeDescrib内作为局部变量，那么当连续很多次调用StatusCodeDescrib函数，就会构造很多次这个变量，代价太大，
 * 内存空间不够了，使得进程崩溃
 * 
 */
static std::unordered_map<int, std::string> statusInfo = 
{
    {100, "Continue"},
    {101, "Switching Protocol"},
    {102, "Processing"},
    {103, "Early Hints"},
    {200, "OK"},
    {201, "Created"},
    {202, "Accepted"},
    {203, "Non-Authoritative Information"},
    {204, "No Content"},
    {205, "Reset Content"},
    {206, "Partial Content"},
    {207, "Multi-Status"},
    {208, "Already Reported"},
    {226, "IM Used"},
    {300, "Multiple Choice"},
    {301, "Moved Permanently"},
    {302, "Found"},
    {303, "See Other"},
    {304, "Not Modified"},
    {305, "Use Proxy"},
    {306, "unused"},
    {307, "Temporary Redirect"},
    {308, "Permanent Redirect"},
    {400, "Bad Request"},
    {401, "Unauthorized"},
    {402, "Payment Required"},
    {403, "Forbidden"},
    {404, "Not Found"},
    {405, "Method Not Allowed"},
    {406, "Not Acceptable"},
    {407, "Proxy Authentication Required"},
    {408, "Request Timeout"},
    {409, "Conflict"},
    {410, "Gone"},
    {411, "Length Required"},
    {412, "Precondition Failed"},
    {413, "Payload Too Large"},
    {414, "URI Too Long"},
    {415, "Unsupported Media Type"},
    {416, "Range Not Satisfiable"},
    {417, "Expectation Failed"},
    {418, "I'm a teapot"},
    {421, "Misdirected Request"},
    {422, "Unprocessable Entity"},
    {423, "Locked"},
    {424, "Failed Dependency"},
    {425, "Too Early"},
    {426, "Upgrade Required"},
    {428, "Precondition Required"},
    {429, "Too Many Requests"},
    {431, "Request Header Fields Too Large"},
    {451, "Unavailable For Legal Reasons"},
    {501, "Not Implemented"},
    {502, "Bad Gateway"},
    {503, "Service Unavailable"},
    {504, "Gateway Timeout"},
    {505, "HTTP Version Not Supported"},
    {506, "Variant Also Negotiates"},
    {507, "Insufficient Storage"},
    {508, "Loop Detected"},
    {510, "Not Extended"},
    {511, "Network Authentication Required"}
};
/**
 * @brief 文件后缀及其mime的对照表
 * 设置为全局变量，只构造一次。
 * 如果放在函数SufMime内作为局部变量，那么当连续很多次调用SufMime函数，就会构造很多次这个变量，代价太大，
 * 内存空间不够了，使得进程崩溃
 * 
 */
static std::unordered_map<std::string, std::string> mimeInfo = 
{
    {".aac", "audio/aac"},
    {".abw", "application/x-abiword"},
    {".arc", "application/x-freearc"},
    {".avi", "video/x-msvideo"},
    {".azw", "application/vnd.amazon.ebook"},
    {".bin", "application/octet-stream"},// 默认文件类ing
    {".bmp", "image/bmp"},
    {".bz", "application/x-bzip"},
    {".bz2", "application/x-bzip2"},
    {".csh", "application/x-csh"},
    {".css", "text/css"},
    {".csv", "text/csv"},
    {".doc", "application/msword"},
    {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot", "application/vnd.ms-fontobject"},
    {".epub", "application/epub+zip"},
    {".gif", "image/gif"},
    {".htm", "text/html"},
    {".html", "text/html"},
    {".ico", "image/vnd.microsoft.icon"},
    {".ics", "text/calendar"},
    {".jar", "application/java-archive"},
    {".jpeg", "image/jpeg"},
    {".jpg", "image/jpeg"},
    {".js", "text/javascript"},
    {".json", "application/json"},
    {".jsonld", "application/ld+json"},
    {".mid", "audio/midi"},
    {".midi", "audio/x-midi"},
    {".mjs", "text/javascript"},
    {".mp3", "audio/mpeg"},
    {".mpeg", "video/mpeg"},
    {".mpkg", "application/vnd.apple.installer+xml"},
    {".odp", "application/vnd.oasis.opendocument.presentation"},
    {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt", "application/vnd.oasis.opendocument.text"},
    {".oga", "audio/ogg"},
    {".ogv", "video/ogg"},
    {".ogx", "application/ogg"},
    {".otf", "font/otf"},
    {".png", "image/png"},
    {".pdf", "application/pdf"},
    {".ppt", "application/vnd.ms-powerpoint"},
    {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar", "application/x-rar-compressed"},
    {".rtf", "application/rtf"},
    {".sh", "application/x-sh"},
    {".svg", "image/svg+xml"},
    {".swf", "application/x-shockwave-flash"},
    {".tar", "application/x-tar"},
    {".tif", "image/tiff"},
    {".tiff", "image/tiff"},
    {".ttf", "font/ttf"},
    {".txt", "text/plain"},
    {".vsd", "application/vnd.visio"},
    {".wav", "audio/wav"},
    {".weba", "audio/webm"},
    {".webm", "video/webm"},
    {".webp", "image/webp"},
    {".woff", "font/woff"},
    {".woff2", "font/woff2"},
    {".xhtml", "application/xhtml+xml"},
    {".xls", "application/vnd.ms-excel"},
    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml", "application/xml"},
    {".xul", "application/vnd.mozilla.xul+xml"},
    {".zip", "application/zip"},
    {".3gp", "video/3gpp"},
    {".3g2", "video/3gpp2"},
    {".7z", "application/x-7z-compressed"}
};

class Utils
{
private:
    /**
     * @brief 将字符型数字转换为整型十进制数
     * 
     * @param ch 要转换的字符
     * @return int8_t 字符型数字对应的整型十进制数
     */
    static int8_t CharToInt8(char ch)
    {
        if(islower(ch)) return ch - 'a' + 10;
        if(isupper(ch)) return ch - 'A' + 10;
        if(isdigit(ch)) return ch - '0';
        return -1;
    }
public:
    /**
     * @brief 字符串分割——将源字符串in以sep为分隔字符串分割，得到的子串存储到out中。不存储空串
     * @param in 源字符串
     * @param sep 分割符(是字符串)
     * @param out 数组，分割源字符串得到的子串依次存储到out中
     */
    static size_t Split(const std::string& in, const std::string& sep, std::vector<std::string>* out)
    {
        size_t startPos = 0;
        size_t sepPos = in.find(sep, startPos);
        while(sepPos != std::string::npos)
        {
            // 去除空串
            if(sepPos != startPos)
            {
                out->push_back(in.substr(startPos, sepPos - startPos));
            }

            startPos = sepPos + sep.size();
            sepPos = in.find(sep, startPos);
        }

        if(startPos < in.size()) out->push_back(in.substr(startPos));

        return out->size();
    }

    /**
     * @brief 以二进制方式读取文件的所有内容，存放到out中
     * 
     * @param fileName 要读取的文件的文件名
     * @param out 字符串，读取到的内容存放到out中
     * @return true 读取成功；
     * @return false 读取失败
     */
    static bool ReadFile(const std::string& fileName, std::string* out)
    {
        // 二进制方式打开文件
        std::ifstream ifs(fileName.c_str(), std::ios::binary);
        if(ifs.is_open() == false)
        {
            ERR_LOG("ReadFile failed: open file failed");
            return false;
        }

        // 获取文件中的数据大小
        ifs.seekg(0, ifs.end);
        int length = ifs.tellg();
        ifs.seekg(0, ifs.beg);

        // 读取数据
        out->resize(length);
        ifs.read(&(*out)[0], length);
        if(ifs.good() == false)
        {
            ERR_LOG("ReadFile failed: read from %s failed", fileName.c_str());
            ifs.close();
            return false;
        }

        ifs.close();
        return true;
    }

    /**
     * @brief 向文件中写入数据
     * 
     * @param fileName 要写入到的文件的文件名
     * @param data 要写入的数据
     * @return true 写入成功；
     * @return false 写入失败
     */
    static bool WriteFile(const std::string& fileName, const std::string& data)
    {
        // 二进制方式打开文件，没有就创建
        std::ofstream ofs(fileName, std::ios::binary);
        if(ofs.is_open() == false)
        {
            ERR_LOG("WriteFile failed: open %s failed", fileName.c_str());
            return false;
        }

        // 写入数据
        ofs.write(data.c_str(), data.size());
        if(ofs.good() == false)
        {
            ERR_LOG("WriteFile failed: write into %s fileName failed", fileName.c_str());
            ofs.close();
            return false;
        }

        ofs.close();
        return true;
    }

    /**
     * @brief URL编码——避免url路径和查询字符串中的特殊字符和HTTP请求中的特殊字符产生歧义。
     * 编码格式：将特殊字符的ASCII码值转换为两个十六进制字符(前缀为%)，如C++转换为C%2B%2B。
     * 在RFC3989文档中规定的URL中绝对不编码字符：._-~ 字母 数字。
     * RFC3986文档规定的编码格式：%HH。
     * W3C文档规定：查询字符串中的空格需要被转换为+。
     * 
     * @param url 要编码的url路径
     * @param convert_space_to_plus 是否采用W3C标准，将空格转换为+
     * @return std::string 编码后的url路径
     */
    static std::string UrlEncode(const std::string& url, bool convert_space_to_plus = false)
    {
        std::string ret;
        
        for(const auto& ch : url)
        {
            if(ch == '.' || ch == '_' || ch == '-' || ch == '~' || isalnum(ch))
            {
                ret += ch;
                continue;
            }

            if(ch == ' ' && convert_space_to_plus)
            {
                ret += '+';
                continue;
            }

            char buffer[4] = { 0 };
            sprintf(buffer, "%%%02X", ch);
            ret += buffer;
        }

        return ret;
    }

    /**
     * @brief URL解码
     * 
     * @param url 要解码的已被加密的url路径
     * @param convert_plus_to_space 是否采用W3C标准，将+转换为空格
     * @return std::string 解码后的url路径
     */
    static std::string UrlDecode(const std::string url, bool convert_plus_to_space = false)
    {
        std::string ret;

        for(int i = 0; i < url.size(); ++i)
        {
            if(url[i] == '%')
            {
                int8_t first = CharToInt8(url[i + 1]);
                int8_t second = CharToInt8(url[i + 2]);
                char buffer[2] = { 0 };
                sprintf(buffer, "%c", first * 16 + second);
                ret += buffer;
                i += 2;
                continue;
            }

            if(url[i] == '+' && convert_plus_to_space) ret += ' ';
            else ret += url[i];
        }

        return ret;
    }

    /**
     * @brief 根据状态码获取状态码描述信息
     * 
     * @param statusCode 状态码
     * @return std::string 状态码对应的描述
     */
    static std::string StatusCodeDescrib(int statusCode)
    {
        auto it = statusInfo.find(statusCode);
        if(it == statusInfo.end()) return "unknown status code";
        return it->second;
    }

    /**
     * @brief 根据文件后缀名获取mime。若没有后缀名，则默认文件为二进制文件，其内容为二进制内容
     * 
     * @param fileName 文件的文件名
     * @return std::string mime；
     * @return "application/octet-stream" 二进制文件和其他文件(mime信息中没有的文件类型)，都返回
     */
    static std::string SufMime(const std::string& fileName)
    {
        auto dotPos = fileName.find_last_of('.');
        if(dotPos == std::string::npos) return "application/octet-stream";

        auto it = mimeInfo.find(fileName.substr(dotPos));
        if(it == mimeInfo.end()) return "application/octet-stream";
        return it->second;
    }

    /**
     * @brief 判断一个文件是否是目录
     * 
     * @param fileName 文件名
     * @return true 是目录
     * @return false 不是目录
     */
    static bool IsDir(const std::string& fileName)
    {
        struct stat st;
        /* int stat(const char *pathname, struct stat *statbuf); */
        int ret = stat(fileName.c_str(), &st);
        if(ret < 0)
        {
            // ERR_LOG("IsDir failed: stat failed");
            return false;
        }

        return S_ISDIR(st.st_mode);
    }

    /**
     * @brief 判断一个文件是否是普通文件
     * 
     * @param fileName 文件名
     * @return true 是普通文件
     * @return false 不是普通文件
     */
    static bool IsRegular(const std::string& fileName)
    {
        struct stat st;
        /* int stat(const char *pathname, struct stat *statbuf); */
        int ret = stat(fileName.c_str(), &st);
        if(ret < 0)
        {
            // ERR_LOG("IsRegular failed: stat failed: %d: %s", errno, strerror(errno));
            return false;
        }

        return S_ISREG(st.st_mode);
    }

    /**
     * @brief 判断请求的资源路径是否合法。
     * 如：/www/index.html，其中最前面的/是根目录，要访问的资源都必须在这个目录层级以下。
     * 不能越界访问根目录外的内容，如：/../file.txt，这是被禁止的。
     * 只检测路径的合法性，不关心正确性
     * 
     * @param path 请求的资源路径
     * @return true 合法
     * @return false 不合法
     */
    static bool ValidPath(const std::string& path)
    {
        // 将资源路径以/为分隔符分割，计算目录层级
        std::vector<std::string> pathMembers;
        Split(path, "/", &pathMembers);
        
        int steps = 0;
        for(auto& subPath : pathMembers)
        {
            if(strcmp(subPath.c_str(), "..") != 0)
            {
                ++steps;
                continue;
            }

            --steps;
            if(steps < 0) return false;
        }

        return true;
    }
};

#endif